package cn.openea.perpartner.meily.web.controller;


import cn.hutool.core.date.DateUtil;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.constant.enums.GoodsTypeEnums;
import cn.openea.perpartner.meily.util.UserContext;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.dto.GoodsDTOFactory;
import cn.openea.perpartner.meily.web.entity.vo.GoodsBatchVo;
import cn.openea.perpartner.meily.web.entity.vo.GoodsVo;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import cn.openea.perpartner.meily.web.service.IOperLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Goods)表控制层
 *
 * @author Weird077
 * @since 2023-01-11 21:04:18
 */
@Api(tags = "商品管理")
@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Resource
    private IGoodsService goodsService;
    @Resource
    private GoodsDTOFactory goodsDTOFactory;
    @Resource
    private IOperLogService operLogService;

    @ApiOperation("商品列表")
    @GetMapping("/page/list")
    public AjaxResult pageList(GoodsVo vo) {
        startPage();
        List<Goods> list = this.goodsService.selectList(vo);
        TableDataInfo dataTable = getDataTable(list);
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", dataTable.getTotal());
        if (vo.isAllStatistics()) {
            // 统计相关数据
            data.put("goodsTypeQuantity", goodsService.goodsStatistics(vo));
        }
        return AjaxResult.success(data);
    }

    @ApiOperation("统计商品各个商品类型的数量")
    @GetMapping("/type/quantity")
    public AjaxResult goodsTypeQuantity(GoodsVo vo) {
        Map<String, Integer> map = goodsService.statisticTypeQuantity(vo);
        return AjaxResult.success(map);
    }

    @ApiOperation("统计商品库商品状态的数量")
    @GetMapping("/status/quantity")
    public AjaxResult goodsStatusQuantity(GoodsVo vo) {
        Map<String, Integer> map = goodsService.statisticStatusQuantity(vo);
        return AjaxResult.success(map);
    }

    @ApiOperation("导出商品信息")
    @PostMapping("/export/excel")
    public void exportCustomerExcel(@RequestBody GoodsBatchVo batchVo, HttpServletResponse response) {
        List<Goods> goodsList;
        if (batchVo.byIds()) {
            // 根据id去查
            List<Long> batchIds = batchVo.getBatchIds();
            if (batchIds.isEmpty()) {
                goodsList = new ArrayList<>();
            } else {
                goodsList = goodsService.listByIds(batchVo.getBatchIds());
            }
        } else {
            goodsList = goodsService.selectList(batchVo.getQueryVO());
        }
        List<GoodsDTOFactory.GoddsExportExcelDTO> exportExcelDTOS = goodsList
                .parallelStream()
                .map(item -> goodsDTOFactory.toExportExcelDTO.apply(item))
                .collect(Collectors.toList());
        // 导出
        ExcelUtil<GoodsDTOFactory.GoddsExportExcelDTO> util = new ExcelUtil<>(GoodsDTOFactory.GoddsExportExcelDTO.class);
        util.exportExcel(response, exportExcelDTOS, "商品列表.xlsx");
    }


    @ApiOperation("相似商品")
    @PostMapping(value = "/similar/list")
    public TableDataInfo similar(@RequestBody GoodsVo goodsVo) {
        List<Goods> list = this.goodsService.similar(goodsVo);
        return getDataTable(list);
    }

    @ApiOperation("商品详情")
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return success(this.goodsService.getById(id));
    }

    @ApiOperation("新增商品")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Goods goods) {
        String goodsType = goods.getGoodsType();
        GoodsTypeEnums instance = GoodsTypeEnums.getInstance(goodsType);
        if (instance == null) {
            return AjaxResult.error("数据异常,请联系系统管理员");
        }
        goods.setCreateUser(UserContext.getUserId());
        goods.setUpdateUser(UserContext.getUserId());
        return toAjax(this.goodsService.save(goods));
    }

    @ApiOperation("修改商品")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Goods goods) {
        String goodsType = goods.getGoodsType();
        GoodsTypeEnums instance = GoodsTypeEnums.getInstance(goodsType);
        if (instance == null) {
            return AjaxResult.error("数据异常,请联系系统管理员");
        }
        goods.setUpdateUser(UserContext.getUserId());
        goods.setUpdateTime(DateUtil.now());
        return toAjax(this.goodsService.updateById(goods));
    }

    @ApiOperation("删除商品")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody List<Long> idList) {
        return toAjax(this.goodsService.removeBatchByIds(idList));
    }

    @ApiOperation("置顶商品")
    @GetMapping("/top/{goodsId}")
    public AjaxResult top(@PathVariable Long goodsId) {
        return toAjax(this.goodsService.top(goodsId));
    }


    @ApiOperation("取消置顶")
    @GetMapping("/top/cancel/{goodsId}")
    public AjaxResult topCancel(@PathVariable Long goodsId) {
        return toAjax(this.goodsService.topCancel(goodsId));
    }

    @ApiOperation("统计商品")
    @PostMapping("/count")
    public AjaxResult selectCount(@RequestBody GoodsVo vo) {
        return AjaxResult.success("操作成功！", this.goodsService.selectCount(vo));
    }

    @ApiOperation("小程序-商品详情")
    @GetMapping("/get/{goodsNo}")
    public AjaxResult findGoodsNo(@PathVariable String goodsNo) {
        return success(this.goodsService.findByGoodsNo(goodsNo));
    }

    @ApiOperation("小程序-商品详情")
    @GetMapping("/get/{goodsNo}/{goodsId}")
    public AjaxResult findGoodsNo(@PathVariable String goodsNo, @PathVariable String goodsId) {
        return success(this.goodsService.queryDetails(goodsNo, goodsId));
    }

    @ApiOperation("小程序-商品列表")
    @PostMapping("/shelf/list")
    public TableDataInfo queryAll(@RequestBody GoodsVo goodsVo) {
        startPage();
        List<Goods> list = this.goodsService.queryAll(goodsVo);
        return getDataTable(list);
    }

    @ApiOperation("获取专区展示商品")
    @GetMapping("/query/zone/show/goods/{goodsType}")
    public AjaxResult queryZoneShowGoods(@PathVariable String goodsType) {
        GoodsTypeEnums goodsTypeEnums = GoodsTypeEnums.getInstance(goodsType);
        Map<String, List<Goods>> zoneGoods = goodsService.queryZoneShowGoods(goodsTypeEnums);
        return AjaxResult.success(zoneGoods);
    }

    @ApiOperation("批量上架,下架,置顶或者取消置顶商品")
    @PostMapping("/batch/{action}")
    public AjaxResult batchOperation(@RequestBody List<Long> ids, @PathVariable String action) {
        if (ids.isEmpty()) {
            return AjaxResult.error("请选择至少一个数据");
        }
        int errNum = 0;
        for (Long id : ids) {
            boolean results = false;
            try {
                switch (action) {
                    case "shelf":
                        goodsService.shelf(id);
                        break;
                    case "down":
                        goodsService.down(id);
                        break;
                    case "top":
                        goodsService.top(id);
                        break;
                    case "offTop":
                        goodsService.topCancel(id);
                        break;
                    default:
                        return AjaxResult.error("错误请求，请重试");
                }
                results = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!results) {
                errNum++;
            }
        }
        if (errNum > 0) {
            return AjaxResult.error(errNum + "处理失败，请重试");
        }
        return AjaxResult.success();
    }

    @ApiOperation("周期数(串)")
    @GetMapping("/cycle/{goodsId}")
    public AjaxResult cycle(@PathVariable Long goodsId) {
        String result = this.goodsService.cycle(goodsId);
        return !"0".equals(result) ? AjaxResult.success("获取周期数成功！", result) : error("获取周期数失败！");
    }

    @ApiOperation("获取未参加到活动的商品")
    @PostMapping("/unactivity/list")
    public TableDataInfo selectProductList(@RequestBody GoodsVo vo) {
        startPage();
        List<Goods> list = this.goodsService.selectProductList(vo);
        return getDataTable(list);
    }

    @ApiOperation("获取未关联企业的商品")
    @GetMapping("/un/relevancy/enterprise/list")
    public TableDataInfo selectUnRelevancyEnterpriseList(GoodsVo vo){
        startPage();
        List<Goods> list = this.goodsService.selectUnRelevancyEnterpriseList(vo);
        return getDataTable(list);
    }

    @ApiOperation("商品分类")
    @GetMapping("/category/{type}")
    public AjaxResult selectProductCategory(@PathVariable String type) {

        return success(goodsService.selectProductCategory(type));
    }

    @ApiOperation("点击量查询")
    @GetMapping("/clicks/{productNum}")
    public AjaxResult queryProductClicks(@PathVariable String productNum) {
        return success(operLogService.queryProductClicks(productNum));
    }

    @ApiOperation("批量复制商品到夏日爆款")
    @PostMapping("/batch/copy")
    public AjaxResult batchCopyGoods(@RequestBody List<Long> idList) {
        String message = goodsService.batchCopyGoods(idList);
        return success(message);
    }

}

